from django.shortcuts import render, redirect
from django.http import Http404, HttpResponse, HttpResponseRedirect, FileResponse, StreamingHttpResponse, JsonResponse
from django.template import loader
from django.urls import reverse
from django.core import mail
from generate_yaml.forms import Syaml, Tyaml
from django.contrib import messages
from Automated_Testing import settings
from Method_Decorate import Decoration, zip_file, Inside_action, Get_django_log
from file_manage import models
from tool.handle.Change_Filename import fill_filename
from tool.handle.Auto_Compile import compile_app
import re
from django.contrib.sessions.models import Session
from requests import session
# 跨站伪造csrf
from django.views.decorators.csrf import csrf_exempt
import json
import time
import sys
import os
import random
import string
import threading
import datetime

# ##############随程序启动调度器
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
from django_apscheduler.jobstores import DjangoJobStore
# 从views引入
from file_manage.views import scheduler as app_scheduler
# jobstores = {
#     'default': DjangoJobStore()
# }
# executors = {
#     'default': ThreadPoolExecutor(20)
# }
# job_defaults = {
#     'max_instance': 4,
# }
# app_scheduler = BackgroundScheduler(jobstores=jobstores,
#                                     executors=executors,
#                                     job_defaults=job_defaults,
#                                     timezone='Asia/Shanghai')
# app_scheduler.start()


###################
@Decoration.check_login
def filename_format(request):
    """
    样本名格式化
    http return :sample_path    search_T  select_mode
    :param request:
    :return:
    """
    user_database = models.User.objects.get(name=request.session['user_id'])
    App_database = models.App.objects.all()
    if request.method == "POST":
        # print("action!")
        # for tmp in range(1,1000000000000):
        #     time.sleep(1)
        #     print(tmp)
        try:
            if request.POST['sample_path']:
                sample_path = request.POST['sample_path']

                search_T = request.POST['search_T']
                one_app_database = models.App.objects.get(name=search_T)
                app_path = one_app_database.app_path
                app_name = one_app_database.short_name
                select_mode = request.POST['select_mode']
                value_return = fill_filename.filename_change(sample_path, app_path, select_mode, user_database,
                                                             app_name)
                if value_return == True:
                    messages.info(request, "改名成功！")
                else:
                    messages.error(request, "改名错误！({0})".format(value_return))
            else:
                messages.error(request, "提交失败！有表单没有填写！")
        except Exception as e:
            # 记录下e
            messages.error(request, "提交失败！错误:{0}".format(e))
        finally:
            return redirect(reverse("tool:format_name"))
    else:  # 当为get的时候
        # pass
        return render(request, "format/filename_format.html", {"username": request.session['user_id'],
                                                               "App_database": App_database, })  # format/filename_format.html


def ajax_progress(request):
    """
    用用户id进行progress查询访问
    :param request:
    :return:
    """
    user_database = models.User.objects.get(name=request.session['user_id'])
    num = user_database.get_progress_bar_value()
    return JsonResponse(num, safe=False)


@Decoration.check_login
def app_compile_view(request):
    """
    app编译状态概览
    :param request:
    :return:
    """
    app_databases_all = models.App.objects.all()  # app所有模型
    task_list_clock = app_scheduler.get_jobs()
    clock_app_pk_list = []
    for tmp in task_list_clock:
        for tmp_app in app_databases_all:
            if tmp.args[0] == tmp_app.pk:
                clock_app_pk_list.append(tmp_app.pk)
    return render(request, 'format/app_compile_view.html',
                  {"app_databases_all": app_databases_all,
                   # "zip_data":zip(app_databases_all,task_list_clock),
                   "task_list_clock": task_list_clock,
                   "clock_app_pk_list": clock_app_pk_list,
                   "username": request.session["user_id"], })


def app_compile_action(request, pk):
    """
    app编译操作！
    :param request:
    :param pk: app主键
    :return:
    """
    app_databases_all = models.App.objects.all()  # app所有模型
    try:
        # compile_app.compile_app.compile_action(pk)
        t = threading.Thread(target=compile_app.compile_app.compile_action, args=[pk, request.session['user_id']])
        t.start()
    except Exception as e:
        Get_django_log.log_action.log_django.error(e)
    finally:
        # return HttpResponseRedirect()
        tmp = reverse("tool:complie_view")
        # kwargs={"app_databases_all": app_databases_all,
        #    "username": request.session["user_id"], })
        # return render(request, 'format/app_compile_view.html',
        #           {"app_databases_all": app_databases_all,
        #            "username": request.session["user_id"], })
        return redirect(tmp)


def inquiry_app_compile(request, pk):
    """
    查询app的编译状态
    :param request:
    :param pk:
    :return:
    """
    # tmp = reverse("tool:format_name")
    # return redirect(tmp)
    tmp_list = compile_app.compile_app.inquery_compile_log(pk)
    temp_html = ""
    for tmp in tmp_list:
        temp_html += "<p>" + tmp + "</p>"
    tmp_doc = '<div class="panel-body" style="height: 100%; overflow-y:scroll">' + \
              '<div style="border: 1px  #000000; width: 100%; margin: 0 auto;">' + temp_html + "</div>" + "</div>"
    return HttpResponse(tmp_doc)


def clock_app_compile(request, pk):
    """
    定时编译app
    :param request:
    :param pk:app主键
    :return:
    """
    app_database = models.App.objects.get(pk=pk)
    if request.method == "POST":
        time_scope = request.POST['time_set'].split(" - ")  # 可能会出现只选择一个时间的情况需要判定
        # interval_time_list=request.POST['interval_time'].split("-")
        interval_time_pattern = re.compile(r'([0-9]{0,4})-([0-9]{0,4})-([0-9]{0,4})')
        interval_time_group = interval_time_pattern.findall(request.POST['interval_time'])
        if not interval_time_group:
            messages.error(request, "输入的间隔时间无法识别！")
            # return redirect(directory_database.get_url())
        interval_time_hours = int(interval_time_group[0][0]) * 7 * 24 + int(interval_time_group[0][1]) * 24 + int(
            interval_time_group[0][2]) * 1
        if (len(time_scope) >= 2):
            set_start_time = time_scope[0]
            set_end_time = time_scope[1]
            minimum_time = (datetime.datetime.now() + datetime.timedelta(minutes=10)).strftime(
                "%Y-%m-%d %H:%M:%S")  # 设定的最小时间
            if set_start_time < minimum_time:  # 时间间隔不得小于十分钟
                # if False:
                messages.error(request, "时间不符要求！")
            elif interval_time_hours == 0:
                app_scheduler.add_job(compile_app.compile_app.compile_action,
                                      # args=[pk,request.session['user_id'] ],
                                      args=[pk, "app", ],
                                      trigger='date',
                                      id=datetime.datetime.now().strftime("%Y_%m_%d_%H-%M-%S"),
                                      run_date=set_start_time, )
            elif interval_time_hours != 0:
                app_scheduler.add_job(compile_app.compile_app.compile_action,
                                      # args=[pk,request.session['user_id'] ],
                                      args=[pk, "app", ],
                                      trigger='interval',
                                      id=datetime.datetime.now().strftime("%Y_%m_%d_%H-%M-%S"),
                                      start_date=set_start_time,
                                      end_date=set_end_time,
                                      hours=interval_time_hours, )
            return HttpResponse("<P>设置完成</p>")

    else:
        return render(request, "share/confirm_clock.html",
                      {"app_database": app_database})


def remove_app_compile_clock_task(request, pk):
    """
    移除编译定时任务
    :param request:
    :param pk:
    :return:
    """

    list_tmp = app_scheduler.get_jobs()
    for tmp in list_tmp:
        if (tmp.args[0] == pk):
            app_scheduler.remove_job(tmp.id)
            # return HttpResponse("删除成功")
    # return HttpResponse("删除失败")
    return redirect(reverse("tool:complie_view"))
